<?php
namespace app\admin\controller;

use Map\Map;
use think\Exception;

class Product extends Common
{
    private $obj;
    public function _initialize()
    {
        parent::_initialize();
        $this->obj = model('Product');
    }

    /**
     * 产品列表
     * @return \think\response\View
     */
    public function index()
    {
        $param = input('param.');
        $where = [];
        $where['delete'] = 1;

        // 组装搜索条件
        // 分类
        if (isset($param['category_id']) &&  $param['category_id'] > 0) {
            $where['category_id'] = $param['category_id'];
        }
        // 产品名
        if (isset($param['name']) && !empty($param['name'])) {
            $where['name'] = ['like', '%' . $param['name'] . '%'];
        }
        // 状态
        if (isset($param['status']) && !empty($param['status'])) {
            $status = explode('_', $param['status']);
            $where[$status[0]] = $status[1];
        }

        // 类型
        if (isset($param['for_sale']) && !empty($param['for_sale'])) {
            $where['for_sale'] = $param['for_sale'];
        }
        // 时间
        if (isset($param['status_time']) && !empty($param['status_time']) && isset($param['end_time']) && !empty($param['status_time'])) {
            $where['create_time'] = ['between time',[strtotime($param['status_time']),strtotime($param['end_time'])]];
        }

        $data = $this->obj->where($where)->order('sort desc, id desc')->paginate(25, false, $param);
        $this->assign('data', $data);
        return view();
    }

    /**
     * 编辑添加保存产品数据
     * @return bool|\think\response\View
     */
    public function product_save() {
        $id = input('param.id', 0);
        if (request()->isPost()) {
            /**
             * 组装数据
             */
            $data['name'] = input('post.name', '');
            $data['sort'] = input('post.sort', 0);
            $data['brand_id'] = input('post.brand_id', 0);
            $data['is_hot'] = input('post.is_hot', 0);
            $data['unit'] = input('post.unit', '');
            $data['scent'] = input('post.scent', '无');
            $data['category_id'] = (int)input('post.category_id', 0);
            $data['price'] = input('post.price', 0);
            $data['is_recommend'] = input('post.is_recommend', 0);
            $data['is_sponsor'] = input('post.is_sponsor', 0);
            $data['ml'] = input('post.ml', 0);
            $data['degree'] = input('post.degree', 0);
            $data['date_in_produced'] = strtotime(input('post.date_in_produced', ''));
            $data['place_of_origin'] = input('post.place_of_origin', 0);
            $data['sponsor_num'] = input('post.sponsor_num', 0);
            $content = input('post.content', '');
            //dump($data);exit;

            /**
             * 验证数据
             */
            $validate = validate('Product');
            if(!$validate->check($data)) {
                $this->error($validate->getError());
            }

            /**
             * 检查角色名是否存在
             */
            $where['id'] = $id > 0 ? ['neq', $id] : ['neq', 0];
            $where['name'] = $data['name'];
            $role = $this->obj->get($where);
            if ($role) {
                $this->error('产品名已存在');
            }

            /**
             * 保存数据
             */
            $where = $id > 0 ? ['id' => $id] : [];
            $rs = $this->obj->save($data, $where);
            if ($rs) {
                $id = $id > 0 ? $id : $this->obj->id;
                $url = '';
                if ($content) {
                    $product_details = model('ProductDetails')->get(['product_id' => $id]);
                    if ($product_details) {
                        $content_data['content'] = $content;
                        model('ProductDetails')->save($content_data, ['product_id' => $id]);
                    } else {
                        $content_data['product_id'] = $id;
                        $content_data['content'] = $content;
                        model('ProductDetails')->save($content_data);
                        $url = url('product_image', ['id' => $id]);
                    }
                }

                // 清理缓存
                \app\api\service\Base::clear_cache();

                $this->success('保存成功', $url);
            } else {
                $this->success('保存失败');
            }
            return true;
        } else {
            $where = ['status' => 1, 'delete' => 1];
            $brand = model('brand')->all($where);
            $this->assign('brand', $brand);

            $where = ['status' => 1, 'delete' => 0];
            $category = model('category')->all($where);
            $this->assign('category', $category);

            $data = [];
            if ($id > 0) {
                $data = $this->obj->get(['id' => $id]);
            }
            $this->assign('data', $data);

            return view();
        }
    }

    /**
     * 产品图片管理
     * @return \think\response\View
     */
    public function product_image() {
        $id = input('param.id');
        if (request()->isPost()) {
            $images =  \app\api\service\Upload::upload_images();
            if ($images['code'] == 0) {
                $this->error('上传失败,' . $images['msg']);
            }
            //dump($images);exit;
            $datas = $images['data'];
            //dump($data);exit;
            $image_data = [];
            foreach ($datas as $k => $v) {
                $image_data[] = [
                    'product_id' => $id,
                    'image' => $v . '-700',
                    'thumb' => $v . '-300'
                ];
            }
            $rs = model('ProductImage')->saveAll($image_data);

            // 清理缓存
            \app\api\service\Base::clear_cache();

            if ($rs) {
                $this->success('上传成功', '', 'reload');
            } else {
                $this->error('上传失败');
            }
        } else {
            $data = model('ProductImage')->where(['product_id' => $id])->order(['delete','sort'=>'desc','id'=>'desc'])->select();
            $this->assign('data', $data);
            $this->assign('id', $id);
        }
        return view();
    }

    /**
     * 设置产品的热销、推荐、赞助、上下架、软删除状态
     */
    public function save_field() {
        try {
            $id = input('param.id', 0);
            $value = input('param.value', 0);
            $field = input('param.field', '');
            if (!$id || !$value) {
                $this->error('参数错误!');
            }
            model('product')->save([$field => $value], ['id' => $id]);
            $this->success('修改成功！');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 设置主图
     */
    public function set_main() {
        try {
            $id = input('param.id');
            $model = model('ProductImage');
            $img = $model->get(['id' => $id]);
            $model->save(['is_main' => 0], ['product_id' => $img['product_id']]);
            $model->save(['is_main' => 1], ['id' => $id]);
            $this->obj->save(['thumb' => $img['thumb'], 'image' => $img['image']], ['id' => $img['product_id']]);
            $this->success('设置成功');
        } catch (Exception $e) {
            $this->success('设置失败');
        }
    }

    /**
     * 删除图片
     */
    public function delete_image() {
        try {
            $id = input('param.id');
            $model = model('ProductImage');
            $img = $model->get(['id' => $id]);
            if (!$img) {
                throw new Exception('图片不存在');
            }
            if ($img->is_main == 1) {
                throw new Exception('产品主图不能删除');
            }

            $model->destroy($id);
            $this->success('删除成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

}
